package com.ita.dom.handler;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.ita.dom.entity.WeiBo;

public class WeiBoDomHandler {

    @SuppressWarnings("unchecked")
	public List<WeiBo> getWeiBoList(File file) throws DocumentException{
    	SimpleDateFormat formatter = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss");
		Date date;
    	
    	List<WeiBo> list=new ArrayList<WeiBo>();
    	SAXReader reader=new SAXReader();
		Document doc=reader.read(file);
		Element weibos=doc.getRootElement();
		Iterator<Element> itor=weibos.elementIterator();
		System.out.println("xml to object:");
		while(itor.hasNext()){
			Element weiboElement=itor.next();
			WeiBo weibo=new WeiBo();
			Iterator<Element> bitor=weiboElement.elementIterator();
			while(bitor.hasNext()){
				Element ele=bitor.next();
				if("id".equalsIgnoreCase(ele.getName())){
					weibo.setId(ele.getText());
				}
				else if("article".equalsIgnoreCase(ele.getName())){
					weibo.setArticle(ele.getText());
				}
				else if("discuss".equalsIgnoreCase(ele.getName())){
					weibo.setDiscuss(ele.getText());
				}
				else if("insertTime".equalsIgnoreCase(ele.getName())){
					date=new Date();
					try {
						date=formatter.parse(ele.getText());
						weibo.setInsertTime(date);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				else if("origin".equalsIgnoreCase(ele.getName())){
					weibo.setOrigin(ele.getText());
				}
				else if("personId".equalsIgnoreCase(ele.getName())){
					weibo.setPersonId(ele.getText());
				}
				else if("time".equalsIgnoreCase(ele.getName())){
					date=new Date();
					try {
						date=formatter.parse(ele.getText());
						weibo.setTime(date);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				else if("transmit".equalsIgnoreCase(ele.getName())){
					if("0".equalsIgnoreCase(ele.getText())){
						Random rand = new Random();
						int randNum = rand.nextInt(100);
						weibo.setTransmit(randNum);
					}
					else{
						weibo.setTransmit(Integer.valueOf(ele.getText()));
					}
				}
			}
			list.add(weibo);
			System.out.println(weibo.toString());
			weibo=null;
		}
    	System.out.println("xml to object end");
		return list;
    	
    }
}
